package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;

/**
 * 报警规则Service业务层处理
 *
 * @author alexis
 * @date 2025-06-05
 */
@Slf4j
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private DeviceMapper deviceMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Value("${alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;
    @Value("${alert.managerRole}")
    private String managerRole;
    @Resource
    private IAlertDataService iAlertDataService;


    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return alertRuleMapper.deleteById(id);
    }

    /**
     * 设备上报数据报警规则过滤任务
     */
    @Override
    public void alertFilter() {
        //查询所有规则个数
        LambdaQueryWrapper<AlertRule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AlertRule::getStatus, 1);
        Long count = alertRuleMapper.selectCount(wrapper);
        if (count < 1) {
            return;
        }

        //查询所有设备上报的数据
        List<Object> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);

        //判断为空直接结束
        if (CollectionUtil.isEmpty(values)) {
            return;
        }

        //数据格式化处理
        List<DeviceData> deviceDataList = new ArrayList<>();
        values.forEach(value -> {
            List<DeviceData> list = JSONUtil.toList(value.toString(), DeviceData.class);
            deviceDataList.addAll(list);
        });

        //调用方法处理上报数据
        deviceDataList.forEach(this::alertFilter);
    }

    private void alertFilter(DeviceData deviceData) {
        //判断当前上报的数据是否超过了1分钟
/*        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 60) {
            return;
        }*/

        //查询对该产品所有设备生效的规则
        LambdaQueryWrapper<AlertRule> allWrapper = new LambdaQueryWrapper<>();
        allWrapper.eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getIotId, "-1")
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getStatus, 1);
        List<AlertRule> allRules = alertRuleMapper.selectList(allWrapper);
        //查询对当前设备生效的规则
        LambdaQueryWrapper<AlertRule> iotWrapper = new LambdaQueryWrapper<>();
        iotWrapper.eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getIotId, deviceData.getIotId())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getStatus, 1);
        List<AlertRule> iotRules = alertRuleMapper.selectList(iotWrapper);
        //合并
        Collection<AlertRule> alertRules = CollectionUtil.addAll(allRules, iotRules);

        //判断是否为空
        if (CollectionUtil.isEmpty(alertRules)) {
            return;
        }

        //遍历每一条规则
        alertRules.forEach(rule -> deviceDataAlarmHandler(rule, deviceData));
    }

    /**
     * 数据报警处理器
     *
     * @param alertRule
     * @param deviceData
     */
    private void deviceDataAlarmHandler(AlertRule alertRule, DeviceData deviceData) {
        //判断生效时间,首先获取 规则的生效时间 00:00:00~23:59:59
        String[] split = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        //获取上报时间
        LocalTime localTime = LocalDateTimeUtil.of(deviceData.getAlarmTime()).toLocalTime();
        if (localTime.isBefore(startTime) || localTime.isAfter(endTime)) {
            return;
        }

        //统计次数的key
        String iotId = deviceData.getIotId();
        String aggCountKey = CacheConstants.IOT_ALERT_TRIGGER_COUNT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();

        //数据对比，上报的数据与规则中的阈值进行对比
        //两个参数x,y(参数有顺序要求，左边是上报的数据，后边是规则的数据)  x==y 返回0  x>y 返回大于0  x<y 返回小于0的数值
        int compare = NumberUtil.compare(Double.parseDouble(deviceData.getDataValue()), alertRule.getValue());
        if ((alertRule.getOperator().equals(">=") && compare >= 0) || (alertRule.getOperator().equals("<") && compare < 0)) {
            //说明当前上报的数据异常
            log.info("当前上报的数据符合规则异常");
            
        } else {
            // 当前上报的数据正常
            // 如果没有达到 redis;删除报警数
            redisTemplate.delete(aggCountKey);
            return;
        }
        //异常的数据会走到这里
        //判断是否在沉默周期内
        String silentKey = CacheConstants.IOT_ALERT_SILENT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        String silentData = redisTemplate.opsForValue().get(silentKey);
        if (StringUtils.isNotEmpty(silentData)) {
            return;
        }
        //持续周期的逻辑,查询报警次数
        String aggData = redisTemplate.opsForValue().get(aggCountKey);
        int count = StringUtils.isEmpty(aggData) ? 1 : Integer.parseInt(aggData) + 1;
        //如果count与持续周期的值相等，则触发报警
        if (ObjectUtil.notEqual(count, alertRule.getDuration())) {
            //不相等
            redisTemplate.opsForValue().set(aggCountKey, count + "");
            return;
        }
        //删除redis的报警数据
        redisTemplate.delete(aggCountKey);
        //存储数据到沉默周期，设置一个过期时间，规则中的沉默周期
        redisTemplate.opsForValue().set(silentKey, "1", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        //报警数据，需要找到对应的人
        List<Long> userIds = new ArrayList<>();
        //判断是老人异常数据
        if (alertRule.getAlertDataType().equals(0)) {
            //老人随身设备
            if (deviceData.getLocationType().equals(0)) {
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            } else {
                //固定设备
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
        } else {
            //设备异常数据
            userIds = sysUserRoleMapper.selectUserIdByRoleName(deviceMaintainerRole);
        }
        //无论那种情况都要通知 超级管理员
        List<Long> managerIds = sysUserRoleMapper.selectUserIdByRoleName(managerRole);

        //合并操作
        Collection<Long> allUserIds = CollectionUtil.addAll(userIds, managerIds);

        //去重
        allUserIds = CollectionUtil.distinct(allUserIds);

        //保存报警数据
        insertAlertData(allUserIds, alertRule, deviceData);
    }

    /**
     * 保存报警数据
     *
     * @param allUserIds
     * @param alertRule
     * @param deviceData
     */
    private void insertAlertData(Collection<Long> allUserIds, AlertRule alertRule, DeviceData deviceData) {
        List<AlertData> list = new ArrayList<>();
        allUserIds.forEach(userId -> {
            AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
            alertData.setAlertRuleId(alertRule.getId());
            //心率<60,持续3个周期就报警
            String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警",
                    alertRule.getFunctionName(),
                    alertRule.getOperator(),
                    alertRule.getValue(),
                    alertRule.getDuration());
            alertData.setAlertReason(alertReason);
            alertData.setStatus(0);
            alertData.setType(alertRule.getAlertDataType());
            alertData.setUserId(userId);
            alertData.setId(null);
            list.add(alertData);
        });
        //批量保存
        iAlertDataService.saveBatch(list);
    }
}
